package org.jeecg.common.util.word;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class UpdateWordTOC {
    public static void main(String[] args) throws IOException {

        String tempPath = "D:\\代码生成图测试\\foot1859145652096995329.docx"; //模板文件路径
        String targetPath2 = "D:\\代码生成图测试\\test2.docx";//生成文件路径
        // 加载现有的Word文档
        FileInputStream fis = new FileInputStream(tempPath);
        XWPFDocument doc = new XWPFDocument(fis);
        fis.close();

        // 刷新目录
//        refreshTOC(doc);

        // 将更新后的文档保存到新文件
        FileOutputStream out = new FileOutputStream(targetPath2);
        doc.write(out);
        out.close();
        doc.close();
    }

    private static void refreshTOC(XWPFDocument doc) {
        // 获取所有段落
        List<XWPFParagraph> paragraphs = doc.getParagraphs();

        // 遍历所有段落，查找目录相关的段落并刷新
        for (XWPFParagraph para : paragraphs) {
            String text = para.getText();
            if (text != null && text.contains("\u007F")) { // 检查是否是目录项
                para.createRun().setText(text, 0); // 更新目录项
            }
        }

        // 更新文档的目录
        doc.enforceUpdateFields();
    }
}
